import axios from 'axios'
import config from '@config'
import Vue from 'vue'
import qs from 'qs'
import router from '@router'
// import Store from 'store'
import $store from '@store'
let instance = axios.create({
  baseURL: config.baseUri
})
let headers = {
  'Content-Type': 'application/json',
  'X-Requested-With': 'XMLHttpRequest',
  'Client-Type': 'wechat'
}
/**
 * @purpose http POST 请求
 * @param path
 * @param data
 * @param type 请求方式 json   formData
 */
export function post (path = '', data = {}, type = 'json') {
  let url = _getApi(path)
  const $vue = new Vue()
  if (!url) {
    $vue.closeLoading()
    return new Promise((resolve, reject) => {
      $vue.toast('参数[path]不可为空!')
      reject(new Error($vue.$lang('参数[path]不可为空!')))
    })
  }
  if (type === 'formData') {
    headers.Accept = '*/*'
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }
  instance.defaults.headers.common['Token'] = $vue.getToken()
  return new Promise((resolve, reject) => {
    instance.post(url, data, {
      headers: headers,
      transformRequest: [data => {
        if (type === 'json') {
          return JSON.stringify(data)
        } else if (type === 'formData') {
          return qs.stringify(data)
        }
      }]
    }).then(r => {
      $vue.closeLoading()
      if (r.status === 200) {
        if (typeof r.data === 'undefined' ||
          r.data === '' ||
          $vue.isEmptyObject(r.data) ||
          !r.data) {
          $vue.toast('服务器响应数据格式错误或为空!')
          reject(r.data)
          return false
        } else if (typeof r.data.code === 'undefined') {
          $vue.toast('服务器未响应状态码!')
          reject(r.data)
          return false
        } else if (r.data.code !== 10000) {
          if (r.data.code === 10004 || r.data.code === 10003) {
            router.push({name: 'mine'})
            $store.dispatch('clearLoginStatus')
          }
          $vue.toast(r.data.message)
          reject(r.data)
          return false
        }
        resolve(r.data)
      } else {
        $vue.toast('网络不给力,稍后再试!')
        reject(new Error('请求错误: ', r))
      }
    }).catch(e => {
      $vue.closeLoading()
      $vue.toast('网络不给力,稍后再试!')
      reject(new Error('请求错误: ', e))
    })
  })
}
/**
 * @purpose http GET 请求
 * @param path
 * @param data
 * @param type 参数类型, ?:表示正常get参数, /:表示符合后端特点的get参数类型  '例如/a/b'
 */
export function get (path = '', data = {}, type = '?') {
  const $vue = new Vue()
  let _data = {}
  let url = _getApi(path)
  if (!url) {
    $vue.closeLoading()
    return new Promise((resolve, reject) => {
      $vue.toast('参数[path]不可为空!')
      reject(new Error($vue.$lang('参数[path]不可为空!')))
    })
  }
  if (type === '/') {
    let param = ''
    for (let i in data) {
      param += `/${data[i]}`
    }
    if (url.lastIndexOf('/') === (url.length - 1)) {
      url = url.substr(0, url.length - 1)
    }
    url += param
  } else if (type === '?') {
    _data = data
  }
  instance.defaults.headers.common['Token'] = $vue.getToken()
  instance.defaults.headers.common['Client-Type'] = 'wechat'
  return new Promise((resolve, reject) => {
    instance.get(url, {params: _data})
      .then(r => {
        $vue.closeLoading()
        if (r.status === 200) {
          if (typeof r.data === 'undefined' ||
            r.data === '' ||
            $vue.isEmptyObject(r.data) ||
            !r.data) {
            $vue.toast('服务器响应数据格式错误或为空!')
            reject(r.data)
            return false
          } else if (typeof r.data.code === 'undefined') {
            $vue.toast('服务器未响应状态码!')
            reject(r.data)
            return false
          } else if (r.data.code !== 10000) {
            if (r.data.code === 10004 || r.data.code === 10003) {
              router.push({name: 'mine'})
              $store.dispatch('clearLoginStatus')
            }
            $vue.toast(r.data.message)
            reject(r.data)
            return false
          }
          resolve(r.data)
        } else {
          $vue.toast('网络不给力,请稍后再试!')
          reject(new Error('请求错误: ', r))
        }
      }).catch(e => {
        $vue.closeLoading()
        $vue.toast('网络不给力,请稍后再试!')
        reject(new Error('请求错误: ', e))
      })
  })
}
/**
 * @purpose 获取api路径
 * @param path
 * @private
 */
function _getApi (path) {
  const $vue = new Vue()
  if (!path) {
    $vue.toast(`Api "${path}" 未定义!`)
    throw new Error($vue.$lang(`Api "${path}" 未定义!`))
  }
  let api = require('@config/api')
  if (api.default) {
    api = api.default
  }
  if (path.indexOf('.') < 0) {
    return api[path]
  }
  path = path.split('.')
  path.forEach(item => {
    api = api[item]
  })
  let baseApi = config.baseApi
  let proxyPrefix = config.proxyPrefix
  if (proxyPrefix.indexOf('/') === 0) {
    proxyPrefix = proxyPrefix.substring(1, proxyPrefix.length)
  }
  if (proxyPrefix.lastIndexOf('/') === proxyPrefix.length - 1) {
    proxyPrefix = proxyPrefix.substring(0, baseApi.length - 1)
  }
  if (api.indexOf('/') === 0) {
    api = api.substring(1, api.length)
  }
  if (baseApi.lastIndexOf('/') === baseApi.length - 1) {
    baseApi = baseApi.substring(0, baseApi.length - 1)
  }
  return `${baseApi}/${proxyPrefix}/${api}`
}
